#include <cmath>
#include <ctime>
#include "../Tools/GLHeaders.hpp"
#include "../Tools/Chrono.hpp"
#include "../Global.hpp"
#include "IdleFunc.hpp"

#if DEBUG
#include <cstdio>
#endif

void SleepGLScene(void){
  static bool init = false;
  static Chrono time;
#if DEBUG
  static Chrono log;
  static float cpt = -1.0f;
#endif
  struct timespec sleep;
  float tmp;

  if(init == false){
    time.Activate();
#if DEBUG
    log.Activate();
#endif
    init = true;
  }
#if DEBUG
  if((float)log.GetTime() > 10.0f){
    fprintf(stderr, "fps : %.1f\n", (float)cpt/log.GetTime());
    cpt = 0.0f;
    log.Reset();
  }
#endif
  if(time.GetTime() > 1.0f/fps){
    time.Reset();
#if DEBUG
    cpt += 1.0f;
#endif
    glutPostRedisplay();
  }
  else{
    tmp = (float)1.0f/fps-time.GetTime();
    sleep.tv_sec = (time_t)floorf(tmp);
    sleep.tv_nsec = (long)((tmp-floorf(tmp))*1000000000);
    nanosleep(&sleep, NULL);
  }
}
